﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
//using System.Configuration;
using UnisysMassiveImporter_v2;
using UnisysMassiveImporter_v2.Entidades.Configuracion;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Win32;
using System.ServiceProcess;
using System.Configuration;

namespace Configurator
{
    public partial class Frm_Main : Form
    {
        public string  threadPath = "";
        
        public Frm_Main()
        {
            InitializeComponent();
           
        }

        private void btn_FindSystemError_Click(object sender, EventArgs e)
        {
            
            fbd_Find.SelectedPath = "C:\\";
            

            DialogResult result = fbd_Find.ShowDialog();
            if (result.ToString() == "OK")
            {
                txt_SystemError.Text = fbd_Find.SelectedPath;
               


            }
        }

        private void btn_FindLogs_Click(object sender, EventArgs e)
        {
            fbd_Find.SelectedPath = "C:\\";


            DialogResult result = fbd_Find.ShowDialog();
            if (result.ToString() == "OK")
            {
               txt_Logs.Text = fbd_Find.SelectedPath;



            }
        }

        private void btn_FindThreads_Click(object sender, EventArgs e)
        {
            fbd_Find.SelectedPath = "C:\\";


            DialogResult result = fbd_Find.ShowDialog();
            if (result.ToString() == "OK")
            {
                threadPath = fbd_Find.SelectedPath;
                 txt_Threads.Text = threadPath;



            }
        }

        private void Frm_Main_Load(object sender, EventArgs e)
        {
            ServiceController sc = new ServiceController("Unisys Massive Importer");
            try
            {
                if (sc == null)
                {
                    MessageBox.Show(null, "El Servicio no se encuentra instalado.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(0);
                }
                else if (sc.Status == ServiceControllerStatus.Running)
                {
                    btn_ServiceP.BackColor = Color.Green;
                }
                else
                {
                    btn_ServiceP.BackColor = Color.Red;
                }

            }
            catch (Exception ex)
            {
                
            }
            CargarAppConfig();
            CargarRegistro();

        }

        public void CargarThreads()
        {
            try
            {
                if (txt_Threads.Text != "")
                {
                    DirectoryInfo dir = new DirectoryInfo(txt_Threads.Text.Trim());
                    foreach (FileInfo file in dir.GetFiles())//se buscan archivos dentro de la carpeta data
                    {
                        if (file.Extension.ToLower().Equals(".xml"))
                        {

                            dgd_Threads.Rows.Add(file.Name.ToString(), file.FullName.ToString());

                        }
                    }
                }
                else {
                }

                
            }
            catch (Exception e)
            {
            }
        }

        private void tabPage2_Click(object sender, EventArgs e)
        {
            if (dgd_Threads.RowCount == 1)
            {
                CargarThreads();
            }
        }

        private void tabControl1_Click(object sender, EventArgs e)
        {
            if (dgd_Threads.RowCount == 1)
            {
                CargarThreads();
            }
        }

        private void dgd_Threads_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
           // threadDirection = ;
            if (Convert.ToString(dgd_Threads.CurrentRow.Cells[1].Value).Equals(""))
            {
                frm_trehad frm = new frm_trehad(txt_Threads.Text.Trim());

                //MessageBox.Show(Convert.ToString(dgd_Threads.CurrentRow.Cells[1].Value));
                frm.Show();
            }
            else
            {
                frm_trehad frm = new frm_trehad(Convert.ToString(dgd_Threads.CurrentRow.Cells[1].Value), txt_Threads.Text.Trim());

                //MessageBox.Show(Convert.ToString(dgd_Threads.CurrentRow.Cells[1].Value));
                frm.Show();
            }

        }

        private void CargarAppConfig()
        {
            string GenerarHistorico, FileSystemHistory, FileSystemError, DireccionLog, Threads_Configurations, EMailAccountTo, LogSize, System;
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(Environment.CurrentDirectory + "/UnisysMassiveImporter_v2.exe.config");
            XmlNodeList configuraciones = xDoc.GetElementsByTagName("appSettings");
            XmlNodeList lista = ((XmlElement)configuraciones[0]).GetElementsByTagName("add");

            foreach (XmlElement nodo in lista)
            {
                switch (nodo.GetAttribute("key"))
                {
                    case "GenerarHistorico":
                        if (nodo.GetAttribute("value").Equals("True"))
                        {
                            cbx_GenerarHistory.SelectedIndex = 1;
                        }
                        else { cbx_GenerarHistory.SelectedIndex = 0; }
                      

                        break;
                    case "FileSystemHistory":
                        txt_history.Text = nodo.GetAttribute("value");

                        break;
                    case "FileSystemError":
                        txt_SystemError.Text = nodo.GetAttribute("value");
                        break;

                    case "DireccionLog":
                        txt_Logs.Text = nodo.GetAttribute("value");
                        break;

                    case "Threads_Configurations":
                        txt_Threads.Text = nodo.GetAttribute("value");
                        break;

                    case "EMailAccountTo":
                       txt_Email.Text = nodo.GetAttribute("value");
                        break;

                    case "LogSize":
                        txt_LogSize.Text = nodo.GetAttribute("value");
                        break;

                    case "System":
                        txt_Sistema.Text = nodo.GetAttribute("value");
                        break;

                }

            }
        }

        private void btn_finHistory_Click(object sender, EventArgs e)
        {
            fbd_Find.SelectedPath = "C:\\";


            DialogResult result = fbd_Find.ShowDialog();
            if (result.ToString() == "OK")
            {
                
                txt_history.Text = fbd_Find.SelectedPath;
            }
        }

        private void btn_SaveAppConf_Click(object sender, EventArgs e)
        {
            try {
                string exePath = System.IO.Path.Combine(
                Environment.CurrentDirectory, "UnisysMassiveImporter_v2.exe");
                System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(exePath);
                Console.WriteLine(exePath);
                AppSettingsSection appS = configuration.AppSettings;



                if (cbx_GenerarHistory.SelectedIndex == 0)
                {
                    appS.Settings.Remove("GenerarHistorico");
                    appS.Settings.Add("GenerarHistorico", "False");
                }
                else
                {
                    appS.Settings.Remove("GenerarHistorico");
                    appS.Settings.Add("GenerarHistorico", "True");
                }

                appS.Settings.Remove("FileSystemHistory");
                appS.Settings.Add("FileSystemHistory", txt_history.Text.Trim());


                appS.Settings.Remove("FileSystemError");
                appS.Settings.Add("FileSystemError", txt_SystemError.Text.Trim());

                appS.Settings.Remove("DireccionLog");
                appS.Settings.Add("DireccionLog", txt_Logs.Text.Trim());

                appS.Settings.Remove("Threads_Configurations");
                appS.Settings.Add("Threads_Configurations", txt_Threads.Text.Trim());

                appS.Settings.Remove("EMailAccountTo");
                appS.Settings.Add("EMailAccountTo", txt_Email.Text.Trim());

                appS.Settings.Remove("LogSize");
                appS.Settings.Add("LogSize", txt_LogSize.Text.Trim());

                appS.Settings.Remove("System");
                appS.Settings.Add("System", txt_Sistema.Text.Trim());

              

                configuration.Save(ConfigurationSaveMode.Modified);

                MessageBox.Show(null, "La configuración ha sido guardada exitosamente.", "Unisys Massive Importer Configurator", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }catch(Exception ex){
                MessageBox.Show(ex.Message);
            }
           

        }

        private void btn_GuardarRegis_Click(object sender, EventArgs e)
        {
            String registry = "HKEY_LOCAL_MACHINE\\Software\\Unisys\\Unisys Massive Importer";
            Registry.SetValue(registry, "Configuration_Error", chx_ConfigurationError.Checked.ToString()); 
            
            Registry.SetValue(registry, "FileSystemLog", chx_FileSystemLog.Checked.ToString()); 

            Registry.SetValue(registry, "IIF_Error", chx_InfoImageError.Checked.ToString()); 

            Registry.SetValue(registry, "Information_Message", chx_IOError.Checked.ToString()); 

             Registry.SetValue(registry, "IO_Error", chx_IOError.Checked.ToString()); 
            
            Registry.SetValue(registry, "Success_Message", chx_SuccessMessage.Checked.ToString()); 

            Registry.SetValue(registry, "System_Error", chx_SystemError.Checked.ToString());

            MessageBox.Show(null, "La configuración  de registro ha sido guardada exitosamente.", "Unisys Massive Importer Configurator", MessageBoxButtons.OK, MessageBoxIcon.Information);


        }

        public void CargarRegistro()
        {
            String registry = "HKEY_LOCAL_MACHINE\\Software\\Unisys\\Unisys Massive Importer";
            if (Registry.GetValue(registry, "Configuration_Error", true).Equals("True"))
            { chx_ConfigurationError.Checked = true; }

            if (Registry.GetValue(registry, "FileSystemLog", true).Equals("True"))
            { chx_FileSystemLog.Checked = true; }

            if (Registry.GetValue(registry, "IIF_Error", true).Equals("True"))
            { chx_InfoImageError.Checked = true;}

            if (Registry.GetValue(registry, "Information_Message", true).Equals("True"))
            { chx_InformationMessage.Checked = true; }

            if (Registry.GetValue(registry, "IO_Error", true).Equals("True"))
            { chx_IOError.Checked =  true; }

            if (Registry.GetValue(registry, "Success_Message", true).Equals("True"))
            { chx_SuccessMessage.Checked = true;}

            if (Registry.GetValue(registry, "System_Error", true).Equals("True"))
            { chx_SystemError.Checked = true; }
        }

        private void DetenerService()
        {
            ServiceController sc = new ServiceController("Unisys Massive Importer");
            try
            {
                if (sc.Status == ServiceControllerStatus.Running)
                {

                    sc.Stop();
                    btn_ServiceP.BackColor = Color.Red;
                }
                sc.WaitForStatus(ServiceControllerStatus.Stopped);
                sc.Close();
               // btn_ServiceP.BackColor = Color.Green;
            }
            catch (Exception ex)
            { }
        }

        private void IniciarServicio()
        {
            ServiceController sc = new ServiceController("Unisys Massive Importer");
            try
            {
                if (sc != null && sc.Status == ServiceControllerStatus.Stopped)
                {

                    sc.Start();
                    btn_ServiceP.BackColor = Color.Green;
                }
                sc.WaitForStatus(ServiceControllerStatus.Running);
                sc.Close();
            }
            catch (Exception ex)
            { }
        }

        private void btn_ServiceP_Click(object sender, EventArgs e)
        {
            if (btn_ServiceP.BackColor.Equals(Color.Green))
            {
                DetenerService();
            }
            else { IniciarServicio(); }
        }

        
        
    }
}
